#include <iostream>
#include <cstring>

using namespace std;

//#define DEBUG
#define MAX_N 10010
int n;
int a[MAX_N];
int s[MAX_N];
//a表示输入的数, s表示是否已经选入一个环

void Process() {
    for (int i = 1; i <= n; ++i) {
        s[i] = 0;
    }

    //一个环一个环的处理
    //对每个环求其长度-1
    //所有环的长度-1之和就是需要调整的次数
    int sum = 0, len = 0;
    int i = 1, start = i, next = a[start];
    do {
        s[i] = 1, start = i, next = a[start];
        len = 1;
        while(next != start) {
            s[next] = 1;
            next = a[next];
            len++;
        }
#ifdef DEBUG
        cout << "len: " << len  << " i: " << i<< endl;
        for (int j = 1; j <= n; ++j) {
            cout << a[j] << ":" << s[j] << "  ";
        }
        cout << endl;
#endif
        sum += (len-1), len = 0;
        while(s[i] == 1 && i <= n) i++;

    }while(i <= n);
    cout << sum << endl;
}

int main() {
    int t;
    cin >> t;
    while(t--) {
        cin >> n;
        for (int i = 1; i <= n; ++i) {
            cin >> a[i];
        }
        Process();
    }
    return 0;
}
